#include "Object.h"

#include "ObjMesh.h"
#include "Material.h"
#include "Ray.h"
#include "Intersection.h"
#include <GL/gl.h>


Object::Object(ObjMesh* mesh, Material* material, const Transform& transform) :
    m_mesh(mesh),
    m_material(material),
    m_transform(transform)
{
}

ObjMesh *Object::getObjMesh()
{
    return m_mesh;
}

Material *Object::getMaterial()
{
    return m_material;
}

Transform &Object::getTransform()
{
    return m_transform;
}

bool Object::intersect(const Ray &ray, Intersection *itsc)
{
    Matrix4f invMatrix = m_transform.invMatrix();
    Ray localRay(invMatrix*ray.o,invMatrix*ray.d);
    bool b = m_mesh->intersect(localRay,itsc);

    if ( b == false )
        return false;

    invMatrix = invMatrix.transposed();
    itsc->n = invMatrix*itsc->n;
    itsc->n.normalize();
    itsc->object = this;

    return true;
}

void Object::draw()
{
    m_material->applyGL();
    glPushMatrix();
    m_transform.applyGL();
    m_mesh->draw();
    glPopMatrix();
}

std::string Object::getName()
{
    return m_name;
}

void Object::setName(const std::string &name)
{
    m_name = name;
}
